import numpy
from flask import Flask, render_template,request,redirect,url_for,jsonify

import pandas as pd
import numpy as np
from frameworks.utils.JsonResult import *
from frameworks.utils.ApiUtil import *
from frameworks.cores.LoadClass import *
from frameworks.cores.Config import *
from controller.MenuController import *
import json
from utils.RedisUtil import *


def create_app():
    app = Flask(__name__)
    app.config['DEBUG'] = True
    return app


app = create_app()

basepath = os.path.join(os.path.dirname(__file__))
config = Config(basepath)

apimap = config.getApi()
env = apimap["base"]
print(env)

loadClass = LoadClass()

jsonResult = JsonResult()

redis = RedisUtil()

@app.route(env+"/login/<string:username>/<string:password>",methods=['GET'])
def login(username,password):
    rs = loadClass.load("controller.UserController","UserController",{"username":username,"password":password})
    return rs

@app.route(env+"/gets/<string:tablename>",methods=['GET'])
def gets(tablename):
    rs = loadClass.load("controller.CommonController","CommonController",{"url":"/gets/"+tablename})
    return rs

@app.route(env+"/get/<string:tablename>/<string:id>",methods=['GET'])
def get(tablename,id):
    rs = loadClass.load("controller.CommonController","CommonController",{"url":"/get/"+tablename+"/"+id})
    return rs

@app.route(env+"/add/<string:tablename>",methods=['POST'])
def add(tablename):
    quert_json = request.get_data(as_text=True)
    print(quert_json)
    query_data = json.loads(quert_json)
    rs = loadClass.load("controller.CommonController","CommonController",{"url":"/add/"+tablename,"params":query_data})
    return rs

@app.route(env+"/update/<string:tablename>/<string:id>",methods=['POST'])
def update(tablename,id):
    quert_json = request.get_data(as_text=True)
    print(quert_json)
    query_data = json.loads(quert_json)
    rs = loadClass.load("controller.CommonController","CommonController",{"url":"/update/"+tablename+"/"+id,"params":query_data})
    return rs

@app.route(env+"/delete/<string:tablename>/<string:id>",methods=['POST'])
def delete(tablename,id):
    rs = loadClass.load("controller.CommonController","CommonController",{"url":"/delete/"+tablename+"/"+id})
    return rs

@app.route(env+"/getslimit/<string:tablename>/<string:begin>/<string:count>",methods=['GET'])
def getslimit(tablename,begin,count):
    rs = loadClass.load("controller.CommonController","CommonController",{"url": "/getslimit/" + tablename + "/" + begin + "/" + count })
    return rs

@app.route(env+"/query/<string:tablename>/<string:selectreg>/<string:wherereg>",methods=['GET'])
def query(tablename,selectreg,wherereg):
    selectreg = selectreg.replace("||", ",")
    wherereg = wherereg.replace("|||", "%20")
    rs = loadClass.load("controller.CommonController","CommonController",{"url": "/query/" + tablename + "/" + selectreg + "/" + wherereg})
    return rs

@app.route(env+"/querylimit/<string:tablename>/<string:selectreg>/<string:wherereg>/<string:begin>/<string:count>",methods=['GET'])
def querylimit(tablename,selectreg,wherereg,begin,count):
    selectreg = selectreg.replace("||", ",");
    wherereg = wherereg.replace("|||", "%20");
    rs = loadClass.load("controller.CommonController","CommonController",{"url": "/querylimit/" + tablename + "/" + selectreg + "/" + wherereg + "/" + begin + "/" + count})
    return rs

@app.route(env+"/get_structure/<string:tablename>",methods=['GET'])
def get_structure(tablename):
    rs = loadClass.load("controller.CommonController","CommonController",{"url": "/get_structure/" + tablename})
    return rs

@app.route(env+"/get_tree/<string:tablename>/<string:id>/<string:level>",methods=['GET'])
def get_tree(tablename,id,level):
    rs = loadClass.load("controller.CommonController","CommonController",{"url": "/get_tree/" + tablename + "/" + id + "/" + level})
    return rs

@app.route(env+"/menu_set",methods=['GET'])
def menu_set():
    con = MenuController({})
    #jsonString = con.getMenuStr()
    #model.addAttribute("jsonString","["+jsonString+"]");
    return "menu_set"

@app.route(env+"/menu_list",methods=['GET'])
def menu_list():
    con = MenuController({})
    rs = con.getMenuList()
    return jsonResult.setOk(len(rs),rs)

@app.route(env+"/menu_gets_json",methods=['GET'])
def menu_gets_json():
    key = "menu_gets_json"
    al = redis.vget(key)
    if al != None:
        print("read cache")
        return jsonResult.setOk(0,json.loads(al))
    con = MenuController({})
    content = con.menu_gets("2","backgroud")
    redis.vset(key, json.dumps(content))
    return jsonResult.setOk(0,content)

@app.route(env+"/front_menu_gets_json",methods=['GET'])
def front_menu_gets_json():
    key = "front_menu_gets_json"
    al = redis.vget(key)
    if al != None:
        print("read cache")
        return jsonResult.setOk(0, json.loads(al))
    con = MenuController({})
    content = con.menu_gets("1","front")
    redis.vset(key, json.dumps(content))
    return jsonResult.setOk(0, content)

@app.route(env+"/menu_gets_all",methods=['GET'])
def menu_gets_all():
    con = MenuController({})
    content = con.menu_gets("2")
    al = content["children"]
    menuStr = ""
    for level1 in al:
        level2 = level1["children"]
        if len(level2) > 0:
            menuStr += "<lay-sub-menu>\n"
            menuStr += "<template #title>\n"+level1["name"]+"\n</template>\n"
            for level3 in level2:
                menuStr += "<lay-menu-item><a href='"+level3["url"]+"'>"+level3["name"]+"</a></lay-menu-item>\n"
            menuStr += "</lay-sub-menu>\n"
        else:
            menuStr += "<lay-menu-item><a href='"+level1["url"]+"'>"+level1["name"]+"</a></lay-menu-item>\n"
    return jsonResult.setOk(0,menuStr)

@app.route(env+"/ele_menu_gets_all",methods=['GET'])
def ele_menu_gets_all():
    con = MenuController({})
    content = con.menu_gets("2")
    menuStr = "<el-menu-item index='/manage_index'>首页</el-menu-item>"
    al = content["children"]
    n = 1
    for level1 in al:
        level2 = level1["children"]
        if len(level2) > 0:
            menuStr += "<el-sub-menu index='"+ str(n) +"'>"
            menuStr += "<template #title>"+level1["name"]+"</template>"
            for level3 in level2:
                menuStr += "<el-menu-item index='"+level3["url"]+"'>"+level3["name"]+"</el-menu-item>"
            menuStr += "</el-sub-menu>"
        else:
            menuStr += "<el-menu-item index='"+level1["url"]+"'>"+level1["name"]+"</el-menu-item>"
        n += 1
    return jsonResult.setOk(0,menuStr)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)